<template>
  <view class="publish-container">
    <!-- 加载状态 -->
    <view v-if="checking" class="loading-container">
      <view class="loading-content">
        <text class="loading-text">检查发布权限中...</text>
      </view>
    </view>

    <!-- 表单内容 -->
    <scroll-view 
      v-else
      class="form-container" 
      scroll-y
      :show-scrollbar="false"
    >
      <!-- 展示标题 -->
      <view class="form-group">
        <view class="form-label">
          <text class="label-text">展示标题</text>
          <text class="required">*</text>
        </view>
        <input 
          v-model="formData.title"
          class="form-input"
          placeholder="请输入（10-20字最佳,限制128字）"
          maxlength="128"
        />
        <view class="form-tip">{{ formData.title.length }}/128</view>
      </view>

      <!-- 所在地 -->
      <view class="form-group">
        <view class="form-label">
          <text class="label-text">所在省份</text>
          <text class="required">*</text>
        </view>
        <view class="picker-wrapper">
          <picker
            :value="selectedProvinceIndex"
            :range="provinces"
            @change="onProvinceChange"
            class="form-picker"
          >
            <view class="picker-content">
              <text class="picker-text" :class="{ placeholder: !provinces[selectedProvinceIndex] }">{{ provinces[selectedProvinceIndex] || '请选择省份' }}</text>
              <text class="arrow">></text>
            </view>
          </picker>
        </view>
      </view>

      <view class="form-group">
        <view class="form-label">
          <text class="label-text">所在城市</text>
          <text class="required">*</text>
        </view>
        <view class="picker-wrapper">
          <picker
            :value="selectedCityIndex"
            :range="cities"
            @change="onCityChange"
            class="form-picker"
          >
            <view class="picker-content">
              <text class="picker-text" :class="{ placeholder: !cities[selectedCityIndex] || cities[selectedCityIndex] === '请先选择省份' }">{{ cities[selectedCityIndex] || '请选择城市' }}</text>
              <text class="arrow">></text>
            </view>
          </picker>
        </view>
      </view>

      <!-- 服务类目 -->
      <view class="form-group">
        <view class="form-label">
          <text class="label-text">服务类目</text>
          <text class="required">*</text>
        </view>
        <view class="picker-wrapper">
          <picker
            :value="selectedCategoryIndex"
            :range="categoryNames"
            @change="onCategoryChange"
            class="form-picker"
          >
            <view class="picker-content">
              <text class="picker-text" :class="{ placeholder: !categoryNames[selectedCategoryIndex] }">{{ categoryNames[selectedCategoryIndex] || '请选择服务类目' }}</text>
              <text class="arrow">></text>
            </view>
          </picker>
        </view>
      </view>

      <!-- 基本服务 -->
      <view class="form-group">
        <view class="form-label">
          <text class="label-text">基本服务</text>
        </view>
        <textarea 
          v-model="formData.basic_services"
          class="form-textarea"
          placeholder="请输入内容"
          maxlength="500"
        />
        <view class="form-tip">{{ formData.basic_services.length }}/500</view>
      </view>

      <!-- 擅长服务 -->
      <view class="form-group">
        <view class="form-label">
          <text class="label-text">擅长服务</text>
        </view>
        <textarea 
          v-model="formData.extended_services"
          class="form-textarea"
          placeholder="请输入内容"
          maxlength="500"
        />
        <view class="form-tip">{{ formData.extended_services.length }}/500</view>
      </view>

      <!-- 售后保证 -->
      <view class="form-group">
        <view class="form-label">
          <text class="label-text">售后保证</text>
        </view>
        <textarea 
          v-model="formData.after_sale_service"
          class="form-textarea"
          placeholder="请输入内容"
          maxlength="500"
        />
        <view class="form-tip">{{ formData.after_sale_service.length }}/500</view>
      </view>

      <!-- 上传图片 -->
      <view class="form-group">
        <view class="form-label">
          <text class="label-text">上传图片</text>
        </view>
        <view class="image-upload">
          <view class="images-list">
            <view 
              v-for="(image, index) in formData.images" 
              :key="index"
              class="image-item"
            >
              <image :src="image" class="uploaded-image" mode="aspectFill"/>
              <view class="image-delete" @click="removeImage(index)">×</view>
            </view>
            <view 
              v-if="formData.images.length < 5"
              class="add-image-btn"
              @click="chooseImage"
            >
              <text class="add-icon">+</text>
              <text class="add-text">上传您的证件照、办公环境、资格案例等(估)</text>
            </view>
          </view>
          <view class="upload-tip">{{ formData.images.length }}/5</view>
        </view>
      </view>

      <!-- 保证金设置 -->
      <view class="form-group">
        <view class="form-label">
          <text class="label-text">保证金</text>
        </view>
        <input 
          v-model="formData.deposit_required"
          class="form-input"
          type="digit"
          placeholder="设置保证金金额（可选）"
        />
        <view class="form-tip">设置保证金有助于提升服务可信度</view>
      </view>
    </scroll-view>

    <!-- 底部按钮 -->
    <view class="bottom-actions">
      <button 
        class="submit-btn"
        :disabled="!canSubmit || submitting"
        @click="submitForm"
      >
        {{ submitting ? '提交中...' : '下一步' }}
      </button>
    </view>

  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { localServiceAPI } from '@/utils/api.js'
import { getProvinces, getCitiesByProvince } from '@/utils/areaData.js'
import CreditChecker from '@/utils/creditChecker.js'

// 省市数据
const provinces = getProvinces()
const selectedProvinceIndex = ref(-1)
const cities = ref(['请先选择省份'])
const selectedCityIndex = ref(-1)

// 服务类目数据 - 从后端动态获取
const serviceCategories = ref([])
const categoryNames = computed(() => serviceCategories.value.map(cat => cat.name))
const selectedCategoryIndex = ref(-1)

// 响应式数据
const formData = ref({
  title: '',
  province: '',
  city: '',
  category_id: null,
  basic_services: '',
  extended_services: '',
  after_sale_service: '',
  images: [],
  deposit_required: ''
})

const submitting = ref(false)
const checking = ref(true)

// 计算属性
const canSubmit = computed(() => {
  return formData.value.title.trim() && 
         formData.value.province && 
         formData.value.city &&
         formData.value.category_id &&
         !submitting.value
})

// 方法定义
/**
 * 获取服务分类列表
 */
const loadServiceCategories = async () => {
  try {
    const result = await localServiceAPI.getCategories()
    if (result.success) {
      serviceCategories.value = result.data
    } else {
      console.error('获取服务分类失败:', result.message)
      uni.showToast({
        title: result.message || '获取服务分类失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('获取服务分类失败:', error)
    uni.showToast({
      title: '获取服务分类失败',
      icon: 'none'
    })
  }
}

/**
 * 省份选择处理
 */
const onProvinceChange = (e) => {
  selectedProvinceIndex.value = e.detail.value
  const selectedProvince = provinces[e.detail.value]
  formData.value.province = selectedProvince
  
  // 重置城市选择
  selectedCityIndex.value = -1
  formData.value.city = ''
  
  // 更新城市列表
  if (selectedProvince) {
    cities.value = getCitiesByProvince(selectedProvince)
  } else {
    cities.value = ['请先选择省份']
  }
}

/**
 * 城市选择处理
 */
const onCityChange = (e) => {
  selectedCityIndex.value = e.detail.value
  formData.value.city = cities.value[e.detail.value]
}

/**
 * 服务类目选择处理
 */
const onCategoryChange = (e) => {
  selectedCategoryIndex.value = e.detail.value
  const selectedCategory = serviceCategories.value[e.detail.value]
  formData.value.category_id = selectedCategory.id
}

/**
 * 选择并上传图片
 */
const chooseImage = () => {
  const remainingCount = 5 - formData.value.images.length
  
  uni.chooseImage({
    count: remainingCount,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: async (res) => {
      // 显示上传进度
      uni.showLoading({
        title: `上传中(0/${res.tempFilePaths.length})...`
      })

      try {
        // 逐个上传图片
        for (let i = 0; i < res.tempFilePaths.length; i++) {
          const tempFilePath = res.tempFilePaths[i]
          
          // 更新上传进度
          uni.showLoading({
            title: `上传中(${i + 1}/${res.tempFilePaths.length})...`
          })
          
          const result = await localServiceAPI.uploadImage(tempFilePath)
          if (result.success) {
            formData.value.images.push(result.data.url)
          } else {
            throw new Error(result.message || '图片上传失败')
          }
        }

        uni.hideLoading()
        uni.showToast({
          title: '图片上传成功',
          icon: 'success'
        })
      } catch (error) {
        uni.hideLoading()
        console.error('图片上传失败:', error)
        uni.showToast({
          title: error.message || '图片上传失败',
          icon: 'none'
        })
      }
    },
    fail: (error) => {
      console.error('选择图片失败:', error)
      uni.showToast({
        title: '选择图片失败',
        icon: 'none'
      })
    }
  })
}

/**
 * 删除图片
 */
const removeImage = (index) => {
  formData.value.images.splice(index, 1)
}

/**
 * 提交表单
 */
const submitForm = async () => {
  if (!canSubmit.value) {
    return
  }

  try {
    submitting.value = true

    // 提交前再次检查额度（双重保险）
    console.log('提交前检查本地服务发布额度...')
    const hasCredit = await CreditChecker.checkLocalServiceCredit({
      fromPage: '/pages/local-services/publish'
    })

    if (!hasCredit) {
      console.log('提交时发现额度不足，已引导用户购买')
      return
    }

    console.log('提交前额度检查通过，继续提交服务...')

    // 准备提交数据
    const submitData = {
      title: formData.value.title.trim(),
      province: formData.value.province,
      city: formData.value.city,
      category_id: formData.value.category_id,
      basic_services: formData.value.basic_services.trim(),
      extended_services: formData.value.extended_services.trim(),
      after_sale_service: formData.value.after_sale_service.trim(),
      images: formData.value.images,
      deposit_required: formData.value.deposit_required ? Number(formData.value.deposit_required) : 0
    }

    console.log('提交数据:', submitData)

    const result = await localServiceAPI.createService(submitData)

    if (result.success) {
      uni.showToast({
        title: '服务创建成功',
        icon: 'success'
      })

      // 本地扣除信用
      CreditChecker.reduceLocalCredit(CreditChecker.CREDIT_TYPES.LOCAL_SERVICE, 1)
      console.log('本地信用已扣除')

      // 跳转到服务管理页面
      setTimeout(() => {
        uni.redirectTo({
          url: '/pages/local-services/my-services'
        })
      }, 1500)
    } else {
      uni.showToast({
        title: result.message || '创建失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('创建服务失败:', error)
    uni.showToast({
      title: '创建服务失败',
      icon: 'none'
    })
  } finally {
    submitting.value = false
  }
}

/**
 * 页面加载时检查发布权限
 */
const checkPublishPermission = async () => {
  try {
    checking.value = true
    
    // 检查本地服务发布额度
    console.log('页面加载：检查本地服务发布额度...')
    const hasCredit = await CreditChecker.checkLocalServiceCredit({
      fromPage: '/pages/local-services/publish'
    })

    if (!hasCredit) {
      console.log('额度不足，用户已被引导到购买页面')
      // 不继续加载页面内容，用户需要先购买额度
      return
    }

    console.log('额度检查通过，加载页面内容')
    // 额度充足，加载服务分类数据
    await loadServiceCategories()
  } catch (error) {
    console.error('检查发布权限失败:', error)
    uni.showToast({
      title: '检查权限失败，请重试',
      icon: 'none'
    })
  } finally {
    checking.value = false
  }
}

// 页面加载时检查权限并获取服务分类数据
onMounted(() => {
  checkPublishPermission()
})

</script>

<style scoped>
.publish-container {
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.form-container {
  flex: 1;
  padding-top: 20rpx;
  padding-bottom: 120rpx;
}

.form-group {
  background-color: #ffffff;
  margin: 20rpx 0;
  padding: 30rpx;
}

.form-label {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.label-text {
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
}

.required {
  color: #ff4757;
  margin-left: 8rpx;
  font-size: 32rpx;
}

.form-input {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #e5e5e5;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #333;
  box-sizing: border-box;
}

.form-input:focus {
  border-color: #22c55e;
}

.form-textarea {
  width: 100%;
  min-height: 120rpx;
  border: 1rpx solid #e5e5e5;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 28rpx;
  color: #333;
  box-sizing: border-box;
  resize: none;
}

.form-textarea:focus {
  border-color: #22c55e;
}

.form-tip {
  margin-top: 10rpx;
  font-size: 24rpx;
  color: #999;
  text-align: right;
}

.picker-wrapper {
  width: 100%;
  height: 88rpx;
  border: 1rpx solid #e5e5e5;
  border-radius: 8rpx;
  box-sizing: border-box;
}

.form-picker {
  width: 100%;
  height: 100%;
}

.picker-content {
  width: 100%;
  height: 88rpx;
  padding: 0 20rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
  background-color: #ffffff;
}

.picker-text {
  font-size: 28rpx;
  color: #333;
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
}

.picker-text.placeholder {
  color: #999;
}

.arrow {
  font-size: 24rpx;
  color: #999;
  height: 88rpx;
  line-height: 88rpx;
}

.image-upload {
  width: 100%;
}

.images-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.image-item {
  position: relative;
  width: 160rpx;
  height: 160rpx;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  border-radius: 8rpx;
}

.image-delete {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  width: 40rpx;
  height: 40rpx;
  background-color: #ff4757;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  font-weight: bold;
}

.add-image-btn {
  width: 160rpx;
  height: 160rpx;
  border: 2rpx dashed #e5e5e5;
  border-radius: 8rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 10rpx;
  box-sizing: border-box;
}

.add-icon {
  font-size: 48rpx;
  color: #999;
  margin-bottom: 8rpx;
}

.add-text {
  font-size: 20rpx;
  color: #999;
  text-align: center;
  line-height: 1.2;
}

.upload-tip {
  margin-top: 10rpx;
  font-size: 24rpx;
  color: #999;
  text-align: right;
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #ffffff;
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #e5e5e5;
}

.submit-btn {
  width: 100%;
  height: 88rpx;
  background-color: #22c55e;
  color: white;
  border: none;
  border-radius: 44rpx;
  font-size: 32rpx;
  font-weight: 600;
}

.submit-btn:disabled {
  background-color: #cccccc;
  color: #999;
}

.submit-btn:active:not(:disabled) {
  background-color: #16a34a;
}

.loading-container {
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.loading-text {
  font-size: 32rpx;
  color: #666;
  margin-top: 20rpx;
}

</style>